#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : main.py
# @Author: Richard Chiming Xu
# @Date  : 2022/3/17
# @Desc  : 服务入口

import tornado.ioloop
import tornado.web
import pandas as pd
import json
import uuid


# 定义统一响应
class Response():
    def __init__(self, code, data, msg):
        self.code = code
        self.data = data
        self.msg = msg

# 响应体转json
def convert2json(Response):
  return {
    'code': Response.code,
    'data': Response.data,
    'msg': Response.msg
  }

class RegisterHandler(tornado.web.RequestHandler):

    def post(self, *args, **kwargs):
        request_body = json.loads(self.request.body.decode())
        user = request_body['username']
        pwd = request_body['password']
        # 检查用户名密码
        if ' ' in user and len(user) > 18:
            return self.write(json.dumps(Response(-1, None, '非法用户名!'),default=convert2json))
        if ' ' in pwd and len(pwd) > 18:
            return self.write(json.dumps(Response(-1, None, '非法密码!'),default=convert2json))
        # 模拟注册
        db_data = pd.read_csv('user.csv') # 模拟读取DB

        db_data = db_data.append({
            'uid': str(uuid.uuid4()),
            'user': user,
            'pwd': pwd
        },ignore_index=True)
        db_data.to_csv('user.csv', index = False) # 模拟写入DB

        self.write(json.dumps(Response(0, request_body,'注册成功!'),default=convert2json))


class LoginHandler(tornado.web.RequestHandler):

    def post(self, *args, **kwargs):
        request_body = json.loads(self.request.body.decode())
        user = request_body['username']
        pwd = request_body['password']

        db_data = pd.read_csv('user.csv')  # 模拟读取DB
        user = db_data[(db_data['user'] == user) & (db_data['pwd'] == pwd)]
        if len(user) > 0:
            self.write(json.dumps(Response(0, request_body,'登录成功!'),default=convert2json))
        else:
            self.write(json.dumps(Response(0, request_body, '登录失败!'), default=convert2json))
def make_app():
    return tornado.web.Application([
        (r"/register", RegisterHandler, ),
        (r"/login", LoginHandler,)
    ])

'''
    注册接口：http://localhost:5000/register
    {
	"username": "ls",
	"password": "root"
    }
    
    登录接口：http://localhost:5000/login
    {
	"username": "ls",
	"password": "root"
    }
'''
if __name__ == "__main__":
    app = make_app()
    app.listen(5000)
    tornado.ioloop.IOLoop.current().start()